<?php

class SlideshowController extends Controller
{
  /**
   * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
   * using two-column layout. See 'protected/views/layouts/column2.php'.
   */
  public $layout = '//layouts/column2';
  
  /**
   * @return array action filters
   */
  public function filters()
  {
    return array(
      'accessControl' // perform access control for CRUD operations
      //'postOnly + delete', // we only allow deletion via POST request
    );
  }
  
  /**
   * Specifies the access control rules.
   * This method is used by the 'accessControl' filter.
   * @return array access control rules
   */
  public function accessRules()
  {
    return array(
      array(
        'allow', // allow authenticated user to perform 'create' and 'update' actions
        'actions' => array(
          'index',
          'view',
          'create',
          'update',
          'sort',
          'delete'
        ),
        'users' => array(
          '@'
        )
      ),
      array(
        'deny', // deny all users
        'users' => array(
          '*'
        )
      )
    );
  }
  
  /**
   * Displays a particular model.
   * @param integer $id the ID of the model to be displayed
   */
  public function actionView($id)
  {
    $this->render('view', array(
      'model' => $this->loadModel($id)
    ));
  }
  
  /**
   * Creates a new model.
   * If creation is successful, the browser will be redirected to the 'view' page.
   */
  public function actionCreate()
  {
    $model          = new Slideshow('create');
    $model->enabled = 1;
    
    if (isset($_POST['Slideshow'])) {
      $model->attributes = $_POST['Slideshow'];
      if (CUploadedFile::getInstanceByName('Slideshow[image]')) {
        $model->image = 'OK';
      }
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          //Insert image
          if (CUploadedFile::getInstanceByName('Slideshow[image]')) {
            $file            = new File();
            $photo           = CUploadedFile::getInstanceByName('Slideshow[image]');
            $file->filename  = $photo->getName();
            $file->filesaved = encodeFilename(time() . '_' . $photo->getName());
            $file->filetype  = 'image';
            $file->folder    = 'slideshow/post-images';
            $photo->saveAs('upload/slideshow/post-images/' . $file->filesaved);
            $file->save();
            $model->image = $file->id;
            //thumbnail 
            $thumb        = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/slideshow/post-images/" . $file->filesaved);
            $thumbnails   = Slideshow::model()->thumbnails;
            foreach ($thumbnails as $thumbnail) {
              $thumb->resize($thumbnail[0], $thumbnail[1]);
              $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
            }
          }
          
          $model->save();
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    $this->render('create', array(
      'model' => $model
    ));
  }
  
  /**
   * Updates a particular model.
   * If update is successful, the browser will be redirected to the 'view' page.
   * @param integer $id the ID of the model to be updated
   */
  public function actionUpdate($id)
  {
    $model        = $this->loadModel($id);
    
    //Image
    $image = File::model()->getFile($model->image);
    
    if (isset($_POST['Slideshow'])) {
      $model->attributes = $_POST['Slideshow'];
      
      $transaction = Yii::app()->db->beginTransaction();
      
      try {
        if ($model->validate()) {
          //Insert image
          if (CUploadedFile::getInstanceByName('Slideshow[image]')) {
            //Delete old image
            if (!empty($image) && file_exists(Yii::app()->basePath . "/../upload/slideshow/post-images/" . $image['save'])) {
              @unlink(Yii::getPathOfAlias("webroot") . "/upload/slideshow/post-images/" . $image['save']);
              $thumbnails = Slideshow::model()->thumbnails;
              foreach ($thumbnails as $thumbnail) {
                if (file_exists(Yii::app()->basePath . "/../upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save'])) {
                  @unlink(Yii::getPathOfAlias("webroot") . "/upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save']);
                }
              }
              $file = File::model()->findByPk($model->image);
              if (!empty($file)) {
                $file->delete();
              }
            }
            //Insert new image
            $file            = new File();
            $photo           = CUploadedFile::getInstanceByName('Slideshow[image]');
            $file->filename  = $photo->getName();
            $file->filesaved = encodeFilename(time() . '_' . $photo->getName());
            $file->filetype  = 'image';
            $file->folder    = 'slideshow/post-images';
            $photo->saveAs('upload/slideshow/post-images/' . $file->filesaved);
            $file->save();
            $model->image = $file->id;
            //thumbnail 
            $thumb        = Yii::app()->image->load(Yii::getPathOfAlias("webroot") . "/upload/slideshow/post-images/" . $file->filesaved);
            $thumbnails   = Slideshow::model()->thumbnails;
            foreach ($thumbnails as $thumbnail) {
              $thumb->resize($thumbnail[0], $thumbnail[1]);
              $thumb->save(Yii::getPathOfAlias("webroot") . "/upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $file->filesaved); //save vao thumb
            }
          }
          
          $model->save();
          
          $transaction->commit();
          $this->redirect(array(
            'view',
            'id' => $model->id
          ));
        }
      }
      catch (Exception $e) {
        $transaction->rollBack();
      }
    }
    
    $this->render('update', array(
      'model' => $model,
      'image' => $image
    ));
  }
  
  /**
   * Deletes a particular model.
   * If deletion is successful, the browser will be redirected to the 'admin' page.
   * @param integer $id the ID of the model to be deleted
   */
  public function actionDelete($id)
  {
    $model   = $this->loadModel($id);
    
    $image = File::model()->getFile($model->image);
    if (!empty($image) && file_exists(Yii::app()->basePath . "/../upload/slideshow/post-images/" . $image['save'])) {
      @unlink(Yii::getPathOfAlias("webroot") . "/upload/slideshow/post-images/" . $image['save']);
      $thumbnails = Slideshow::model()->thumbnails;
      foreach ($thumbnails as $thumbnail) {
        if (file_exists(Yii::app()->basePath . "/../upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save'])) {
          @unlink(Yii::getPathOfAlias("webroot") . "/upload/slideshow/thumbs_$thumbnail[0]x$thumbnail[1]/" . $image['save']);
        }
      }
      $image->delete();
    }
    $model->delete();
    
    // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
    if (!isset($_GET['ajax']) && !isset($_GET['action']))
      $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array(
        'index'
      ));
  }
  
  
  /**
   * Manages all models.
   */
  public function actionIndex()
  {
    $model = new Slideshow('search');
    $model->unsetAttributes(); // clear any default values
    
    if (isset($_GET['Slideshow']))
      $model->attributes = $_GET['Slideshow'];
    
    if (isset($_GET['pageSize'])) {
      Yii::app()->user->setState('pageSize', (int) $_GET['pageSize']);
      unset($_GET['pageSize']); // would interfere with pager and repetitive page size change
    }
    
    $this->render('index', array(
      'model' => $model
    ));
  }
  
  public function actionSort()
  {
    if (Yii::app()->request->isAjaxRequest) {
      if (isset($_POST['items']) && is_array($_POST['items'])) {
        $i = 0;
        foreach ($_POST['items'] as $item) {
          $slideshow       = Slideshow::model()->findByPk($item);
          $slideshow->sort = $i;
          $slideshow->update();
          $i++;
        }
      }
    }
  }
  
  /**
   * Returns the data model based on the primary key given in the GET variable.
   * If the data model is not found, an HTTP exception will be raised.
   * @param integer $id the ID of the model to be loaded
   * @return Slideshow the loaded model
   * @throws CHttpException
   */
  public function loadModel($id)
  {
     $model = Slideshow::model()->findByAttributes(array(
      'id' => $id,
    ));
    if ($model === null)
      throw new CHttpException(404, 'The requested page does not exist.');
    return $model;
  }
}